// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/benchmark.h>
#include <melon/init/init.h>

#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

// This runs two sets of benchmarks:
// 1) Benchmark executing expressions wrapped in try compared to executing the
// same expressions without.
// It sums 50 integer columns to create a deep tree of expressions, and runs
// it with no Try expression, a single Try expression around the entire sum,
// and a Try around each individual addition. No exceptions are thrown or
// caught in these benchmarks.
// 2) Benchmark the performance impact of throwing exceptions and catching them
// using Try.
// It divides two integers, using division by 0 to trigger an exception getting
// thrown.
// These benchmarks show that meerly adding a Try expression does not
// significantly impact performance, and the performance cost of handling
// exceptions scales linearly with the number of rows that saw exceptions.

using namespace kumo::pollux;

namespace {
class TryBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  TryBenchmark() : FunctionBenchmarkBase() {
    functions::prestosql::registerAllScalarFunctions();
  }

  RowVectorPtr makeData(vector_size_t numArgs) {
    const vector_size_t size = 1'000;

    std::vector<VectorPtr> args;

    for (vector_size_t i = 0; i < numArgs; ++i) {
      args.emplace_back(vectorMaker_.flat_vector<int32_t>(
          // Add 1 so we don't accidentally end up with any 0s for the division
          // test.
          size,
          [i](vector_size_t row) { return (row * i) + 1; }));
    }

    return vectorMaker_.row_vector(args);
  }

  // Baseline does not use any try.
  size_t runBaseline(vector_size_t numArgs) {
    melon::BenchmarkSuspender suspender;
    auto row_vector = makeData(numArgs);

    std::string expression = "c0 + c1";
    for (vector_size_t i = 2; i < numArgs; ++i) {
      expression += fmt::format(" + c{}", i);
    }

    auto exprSet = compileExpression(expression, row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t runWithOuterTry(vector_size_t numArgs) {
    melon::BenchmarkSuspender suspender;
    auto row_vector = makeData(numArgs);

    std::string expression = "c0 + c1";
    for (vector_size_t i = 2; i < numArgs; ++i) {
      expression += fmt::format(" + c{}", i);
    }
    expression = fmt::format("try({})", expression);

    auto exprSet = compileExpression(expression, row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t runWithNestedTries(vector_size_t numArgs) {
    melon::BenchmarkSuspender suspender;
    auto row_vector = makeData(numArgs);

    std::string expression = "try(c0 + c1)";
    for (vector_size_t i = 2; i < numArgs; ++i) {
      expression = fmt::format("try({} + c{})", expression, i);
    }

    auto exprSet = compileExpression(expression, row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t runDivisionWithNoExceptions() {
    melon::BenchmarkSuspender suspender;
    auto row_vector = makeData(2);

    auto exprSet = compileExpression("TRY(c0 / c1)", row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t runDivisionWithOneException() {
    melon::BenchmarkSuspender suspender;
    auto numerators = makeData(1)->childAt(0);
    auto denominatorValues = std::vector<int32_t>(numerators->size(), 1);
    denominatorValues[0] = 0; // NOLINT
    auto denominators = vectorMaker_.flat_vector(denominatorValues);
    auto row_vector = vectorMaker_.row_vector({numerators, denominators});

    auto exprSet = compileExpression("TRY(c0 / c1)", row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t runDivisionWithAllExceptions() {
    melon::BenchmarkSuspender suspender;
    auto numerators = makeData(1)->childAt(0);
    auto denominatorValues = std::vector<int32_t>(numerators->size(), 0);
    auto denominators = vectorMaker_.flat_vector(denominatorValues);
    auto row_vector = vectorMaker_.row_vector({numerators, denominators});

    auto exprSet = compileExpression("TRY(c0 / c1)", row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t doRun(exec::ExprSet& exprSet, const RowVectorPtr& row_vector) {
    int cnt = 0;
    for (auto i = 0; i < 100; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    return cnt;
  }
};

BENCHMARK_MULTI(baseline) {
  TryBenchmark benchmark;
  return benchmark.runBaseline(50);
}

BENCHMARK_MULTI(singleOuterTry) {
  TryBenchmark benchmark;
  return benchmark.runWithOuterTry(50);
}

BENCHMARK_MULTI(nestedTries) {
  TryBenchmark benchmark;
  return benchmark.runWithNestedTries(50);
}

BENCHMARK_MULTI(divideNoExceptions) {
  TryBenchmark benchmark;
  return benchmark.runDivisionWithNoExceptions();
}

BENCHMARK_MULTI(divideOneException) {
  TryBenchmark benchmark;
  return benchmark.runDivisionWithOneException();
}

BENCHMARK_MULTI(divideAllExceptions) {
  TryBenchmark benchmark;
  return benchmark.runDivisionWithAllExceptions();
}
} // namespace

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};

  melon::runBenchmarks();
  return 0;
}
